<?php


class UsersController extends AppController {
    
    // define controller name
    var $name = 'Users';
    
    // define list of models to use 
    var $uses = array('User','Right','Role');
    
    // set controller domain
    var $controllerDomain = 'users';
    
    public function beforeFilter() {
        parent::beforeFilter();
        
    }
    
    public function isAuthorized() {
        
        $authotrized = parent::isAuthorized();
        
        //TODO
        
        return $authotrized;
    }
    
    public function login() {
      
        // if the user is authenticated perform deauthentification
        if ($this->Auth->user('id')) {
            $this->Auth->logout();
            $this->redirect($this->Auth->logoutRedirect);
        }
        
        // if the login credentials are correct then redirect to proper page
        if ($this->Auth->login()) {
            $this->redirect($this->Auth->loginRedirect);
        }

        // if authentification fails set error message
        if ($this->request->is('post')) {
            $this->Session->setFlash(__('Invaid login credentials',true));
        }
 
    }
    
    public function logout() {
        $this->Auth->logout();
        $this->redirect($this->Auth->logoutRedirect);
    }
    
    // create new record
    public function create() {
        
        // get available roles
        $availableRoles = $this->User->getAvailableRoles($this,$this->Auth->user('role_id'));
        $this->set('availableRoles',$availableRoles);
        
        // create user
        if ($this->request->is('post')) {
            
            //get a random password
            $randomPassword = $this->User->getRandomPassword();
            $this->request->data['User']['retype_password'] =  $randomPassword;
            $this->request->data['User']['password'] = $this->User->hashPassword($randomPassword);
            
            if ($this->User->sanitizeAll() && $this->User->validates() && $this->User->save($this->request->data)) {
                $this->Session->setFlash(__('User created',true)); 
                $this->redirect(array('controller' => 'users','action' => 'index'));             
            }      
            
            $this->Session->setFlash(__('Please correct the mistakes below',true)); 
        }
    }
    
    public function delete($id = null) {
       
        if (!$this->User->activeRecordExists($id)) {   
            $this->Session->setFlash(__('Invalid request',true));
            $this->redirect(array('controller' => 'users','action' => 'index'));           
        }
        
        $this->User->delete($id);
        $this->Session->setFlash(__('Account deleted',true));
        $this->redirect(array('controller' => 'users','action' => 'index'));  
    }
    
    public function edit($id = null) {
        
        // get db record
        $dbUser = $this->User->getActiveRecord($id);
        if ($dbUser == null) {
            $this->Session->setFlash(__('Invalid request',true));
            $this->redirect(array('controller' => 'users','action' => 'index'));
        }
        
        // get available roles
        $availableRoles = $this->User->getAvailableRoles($this,$this->Auth->user('role_id'));
        $this->set('availableRoles',$availableRoles);
        
        // set data for modifications
        if ($this->request->is('get')) {
            $this->request->data = $dbUser;
            $this->request->data['User']['password']        = $this->User->pseudoPassword;
            $this->request->data['User']['retype_password'] = $this->User->pseudoPassword;
        }
        
        // process modifications
        if ($this->request->is('post')) {
            
            $this->User->create();
            $this->User->id = $id;
            
            if ($this->request->data['User']['password'] == $this->User->hashPassword($this->pseudoPassword)) {
                unset($this->request->data['User']['password']);
                unset($this->request->data['User']['retype_password']);
            }
        
            if ($this->User->sanitizeAll() && $this->User->validates() && $this->User->save($this->request->data)) { 
                $this->Session->setFlash(__('User updated',true));
                $this->redirect(array('controller' => 'users','action' => 'index'));              
            }
            
            $this->Session->setFlash(__('Please correct the mistakes below',true));
        } 
    }
    
    public function view($id = null) {
        //todo
    }
    
    public function index() {
        //todo
    }
    
    public function getItems() {
        $this->setAjaxLayout();//todo
        
        $conditions = array();
        $allowed = array();
        
        // get query conditions
        $sidx = (string) @$this->request->query['sidx'];        //sort field
        $sord = (string) @$this->request->query['sord'];        //sort direction
        $rows = intval( @$this->request->query['rows'] );       //rows per page
        $page = intval( @$this->request->query['page'] );       // page number
        
        
        // check conditions range
        if ( $rows > 100 || $rows < 0 || $rows == null ) {
            $rows = 10;
        }
            
        if ( $rows < 0 || $page == null ) {
            $page = 1;
        }
        
        // process filters
        if (@$this->request->query['_search'] === 'true') {
            
            $filters = json_decode(@$this->request->query['filters']);
            $filters = @$filters->rules;
            
            if (is_array($filters) && !empty($filters)) {
                
                foreach ($filters as $filter) {
                    
                    if (!property_exists( $filter, 'field') || !property_exists($filter, 'data') || !in_array($filter->field,$allowed)) {
                        continue;
                    }
                    
                    switch ( $filter->field ) {
                        case 'role':
                            break;
                        default:
                            $conditions[$filter->field] = trim((string)$filter->data);
                    }
                }
            }
        }
        
        
        
        
    }
    
    
/*
		
		$total = $this->User->find( 'count', array( 'conditions' => $conditions, 'fields' => $fields ));
		$this->paginate = array(
			'conditions' => $conditions,
			'limit' => $rows,
			'order' => array( $sortfield => $sortdir )
		);
		$users = $this->paginate( 'User' );

		if ( $total == 0 )
			$page = 0;

		$this->response = array( "page" => $page, "total" => ceil( $total / $rows ), "records" => $total, "rows" => array( ) );

		$counter = 0;
		foreach ( $users as $u ) {
			$u = $u['User'];

			$row = array( 'id' => $u["id"], 'cell' => array(
					$u["user_name"],
					$u["full_name"],
					$this->privileges[$u['rank']],
					($u['active'] == 1)? 'activ' : 'suspendat',
					$u["created"],
			) );

			array_push( $this->response["rows"], $row );
			$counter++;
		}

		return json_encode($this->response);
    */
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}

?>
